package com.hy.demo.util;

import com.hy.frame.util.LogUtil;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * 判断Android设备是否拥有Root权限
 */
public class RootUtil {

    private final static String TAG = "RootUtil";

    public static boolean isRoot() {
        return exeCmdWithRoot("clear");
//        String binPath = "/system/bin/su";
//        String xBinPath = "/system/xbin/su";
//        if (new File(binPath).exists() && isExecutable(binPath))
//            return true;
//        return new File(xBinPath).exists() && isExecutable(xBinPath);
    }

    private static boolean isExecutable(String filePath) {
        Process p = null;
        try {
            p = Runtime.getRuntime().exec("ls -l " + filePath);
            // 获取返回内容
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String str = in.readLine();
            LogUtil.i(TAG, str);
            if (str != null && str.length() >= 4) {
                char flag = str.charAt(3);
                if (flag == 's' || flag == 'x')
                    return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (p != null) {
                p.destroy();
            }
        }
        return false;
    }

    public static boolean exeCmdWithRoot(String cmdStr) {
        if (null == cmdStr || cmdStr.length() == 0) {
            LogUtil.d(TAG, "bad cmdStr");
            return false;
        }
        return exeCmdWithRoot(new String[]{cmdStr});
    }

    public static boolean exeCmdWithRoot(String[] cmds) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("su");
            if (null == cmds || cmds.length == 0 ){
                LogUtil.d(TAG, "bad cmdStr");
            } else {
                DataOutputStream os = new DataOutputStream(process.getOutputStream());
                for (String cmd : cmds) {
                    os.write((cmd + "\n").getBytes());
                }
                os.flush();
                os.close();
            }

        } catch (Exception e) {
            String message = "executeCmd: " + Arrays.toString(cmds) + " error: " + e.toString();
            LogUtil.d(TAG, "errorMessage:" + message);
        }

        if (process != null) {
            LogUtil.d(TAG, "process wait execed");
            try {
                int status = -1;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    if (process.isAlive()) {
                        process.waitFor(1, TimeUnit.SECONDS);
                    }
                } else {
                    status = process.exitValue();
                }
                process.getOutputStream().close();
                process.getErrorStream().close();
                process.getInputStream().close();
                process.destroy();
                LogUtil.d(TAG, "status:" + status);
                //这里是关键代码，其实只有status为1的时候是没有权限，这里个人直接把所有运行shell命令的异常都归为失败
                return 0 == status;
            } catch (InterruptedException e) {
                LogUtil.d(TAG, "InterruptedException");
                e.printStackTrace();
            } catch (IOException e) {
                LogUtil.d(TAG, "IOException");
                e.printStackTrace();
            }
        }
        return false;
    }
}